#include "headfiles.h"

using namespace std;

bool calcHits(Color *solution, 
              Color *guess, 
              int N, 
              int &hit_num, 
              int &pseudo_hit_num) {
    if (solution == NULL ||
        guess == NULL ||
        N <= 0) {
        cout << "Invalid argument, NULL!" << endl;
        return false;
    }

    // flag to indicate matched location
    bool *flag = (bool *)malloc(sizeof(bool) * N);
    if (flag == NULL) {
        cout << "Allocate flag array error, NULL!" << endl;
        return false;
    }
    memset(flag, 0, sizeof(bool) * N);

    // Calculate the number of hits
    int i;
    hit_num = 0;
    for (i = 0; i < N; i++) {
        if (solution[i] == guess[i]) {
            flag[i] == true;
            ++hit_num;
        }
    }

    // Calc the number of psuedo hit
    int *solution_count = (int *)malloc(4 * sizeof(int));
    int *guess_count = (int *)malloc(4 * sizeof(int));
    if (solution_count == NULL ||
        guess_count == NULL) {
        cout << "Buffer allocation error, NULL!" << endl;
        return false;
    }
    memset(solution_count, 0, sizeof(int) * 4);
    memset(guess_count, 0, sizeof(int) * 4);

    for (i = 0; i < N; i++) {
        if (flag[i] == false) {
            ++solution_count[solution[i]];
            ++guess_count[guess[i]];
        }
    }

    int color_index;
    pseudo_hit_num = 0;
    for (color_index = Red; color_index <= Blue; color_index++) {
        pseudo_hit_num += (solution_count[color_index] > guess_count[color_index]) ?
                           guess_count[color_index] : solution_count[color_index];
    }

    free(flag);
    free(solution_count);
    free(guess_count);

    return true;
}


